package org.jeecg.modules.demo.ch.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.ch.Utils.DateUtil;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.WeeklyReportFeedback;
import org.jeecg.modules.demo.ch.service.IWeeklyReportFeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 周报反馈系统
 * @Author: jeecg-boot
 * @Date: 2022-11-14
 * @Version: V1.0
 */
@Api(tags = "周报反馈系统")
@RestController
@RequestMapping("/ch/weeklyReportFeedback")
@Slf4j
public class WeeklyReportFeedbackController extends JeecgController<WeeklyReportFeedback, IWeeklyReportFeedbackService> {
    @Autowired
    private IWeeklyReportFeedbackService weeklyReportFeedbackService;

    @Lazy
    @Autowired
    private CommonAPI commonApi;

    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    /**
     * 分页列表查询
     *
     * @param weeklyReportFeedback
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "周报反馈系统-分页列表查询")
    @ApiOperation(value = "周报反馈系统-分页列表查询", notes = "周报反馈系统-分页列表查询")
//    @GetMapping(value = "/list")
    // 需要将前端将list请求地址改成此地址
    @GetMapping(value = "/mpList")
    @PermissionData(pageComponent = "weekReport/WeeklyReportFeedbackList")
    public Result<IPage<WeeklyReportFeedback>> queryPageList(WeeklyReportFeedback weeklyReportFeedback,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
//		QueryWrapper<WeeklyReportFeedback> queryWrapper = QueryGenerator.initQueryWrapper(weeklyReportFeedback, req.getParameterMap());
        //加载数据权限
        QueryWrapper<WeeklyReportFeedback> queryWrapper = new QueryWrapper<>();
        //调用这个QueryGenerator.installAuthMplus方法加载数据权限
        QueryGenerator.installAuthMplus(queryWrapper, WeeklyReportFeedback.class);
        //开始自己的业务查询
        LambdaQueryWrapper<WeeklyReportFeedback> weeklyReportFeedbackLambdaQueryWrapper = queryWrapper.lambda();
        String weeklyMeetTitle = weeklyReportFeedback.getWeeklyMeetTitle();//周会标题
        String representation = weeklyReportFeedback.getRepresentation();//待办事项
        String classification = weeklyReportFeedback.getClassification();//分类
        String executionStatus = weeklyReportFeedback.getExecutionStatus();//执行状态
        String executor = weeklyReportFeedback.getExecutor();//执行人
        weeklyReportFeedbackLambdaQueryWrapper.like(StringUtils.hasLength(weeklyMeetTitle), WeeklyReportFeedback::getWeeklyMeetTitle, weeklyMeetTitle);
        weeklyReportFeedbackLambdaQueryWrapper.like(StringUtils.hasLength(representation), WeeklyReportFeedback::getRepresentation, representation);
        weeklyReportFeedbackLambdaQueryWrapper.like(StringUtils.hasLength(executor), WeeklyReportFeedback::getExecutor, executor);
        weeklyReportFeedbackLambdaQueryWrapper.eq(StringUtils.hasLength(classification), WeeklyReportFeedback::getClassification, classification);
        weeklyReportFeedbackLambdaQueryWrapper.eq(StringUtils.hasLength(executionStatus), WeeklyReportFeedback::getExecutionStatus, executionStatus);
        weeklyReportFeedbackLambdaQueryWrapper.orderByDesc(WeeklyReportFeedback::getCreateTime);
        weeklyReportFeedbackLambdaQueryWrapper.orderByDesc(WeeklyReportFeedback::getExecutor);
        Page<WeeklyReportFeedback> page = new Page<WeeklyReportFeedback>(pageNo, pageSize);
        IPage<WeeklyReportFeedback> pageList = weeklyReportFeedbackService.page(page, weeklyReportFeedbackLambdaQueryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param weeklyReportFeedback
     * @return
     */
    @AutoLog(value = "周报反馈系统-添加")
    @ApiOperation(value = "周报反馈系统-添加", notes = "周报反馈系统-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:weekly_report_feedback:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WeeklyReportFeedback weeklyReportFeedback) {
        Result<String> stringResult = generateWeeklyTitle();
        String title = stringResult.getResult();
        weeklyReportFeedback.setWeeklyMeetTitle(title);
        String executionStatus = weeklyReportFeedback.getExecutionStatus();
        if (!StringUtils.hasLength(executionStatus)){
            executionStatus=CommonMst.WEEKLYREPORT.EXECUTIONSTATUS2;
        }
        if (executionStatus.equals(CommonMst.WEEKLYREPORT.EXECUTIONSTATUS)){
            weeklyReportFeedback.setActualCompletionTime(new Date());
        }
        weeklyReportFeedbackService.save(weeklyReportFeedback);
        //推送消息
//		iSysBaseAPI.sendTemplateMessage();

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param weeklyReportFeedback
     * @return
     */
    @AutoLog(value = "周报反馈系统-编辑")
    @ApiOperation(value = "周报反馈系统-编辑", notes = "周报反馈系统-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:weekly_report_feedback:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WeeklyReportFeedback weeklyReportFeedback) {
        String executionStatus = weeklyReportFeedback.getExecutionStatus();
        if (StringUtils.hasLength(executionStatus) && CommonMst.WEEKLYREPORT.EXECUTIONSTATUS.equals(executionStatus)) {
            weeklyReportFeedback.setActualCompletionTime(new Date());
        } else if (StringUtils.hasLength(executionStatus) && !CommonMst.WEEKLYREPORT.EXECUTIONSTATUS.equals(executionStatus)) {
            weeklyReportFeedback.setActualCompletionTime(null);
            LambdaUpdateWrapper<WeeklyReportFeedback> updateWrapper = new UpdateWrapper<WeeklyReportFeedback>().lambda()
                    .eq(WeeklyReportFeedback::getId, weeklyReportFeedback.getId())
                    .set(WeeklyReportFeedback::getActualCompletionTime, null);
            weeklyReportFeedbackService.update(updateWrapper);
        }
        weeklyReportFeedbackService.updateById(weeklyReportFeedback);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "周报反馈系统-通过id删除")
    @ApiOperation(value = "周报反馈系统-通过id删除", notes = "周报反馈系统-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:weekly_report_feedback:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        weeklyReportFeedbackService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "周报反馈系统-批量删除")
    @ApiOperation(value = "周报反馈系统-批量删除", notes = "周报反馈系统-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:weekly_report_feedback:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.weeklyReportFeedbackService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "周报反馈系统-通过id查询")
    @ApiOperation(value = "周报反馈系统-通过id查询", notes = "周报反馈系统-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WeeklyReportFeedback> queryById(@RequestParam(name = "id", required = true) String id) {
        WeeklyReportFeedback weeklyReportFeedback = weeklyReportFeedbackService.getById(id);
        if (weeklyReportFeedback == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(weeklyReportFeedback);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param weeklyReportFeedback
     */
    //@RequiresPermissions("org.jeecg.modules.demo:weekly_report_feedback:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WeeklyReportFeedback weeklyReportFeedback) {
        return super.exportXls(request, weeklyReportFeedback, WeeklyReportFeedback.class, "周报反馈系统");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("weekly_report_feedback:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WeeklyReportFeedback.class);
    }

    /**
     * 批量完成
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "周报反馈系统-批量完成")
    @ApiOperation(value = "周报反馈系统-批量完成", notes = "周报反馈系统-批量完成")
    @GetMapping(value = "/completeBatch")
    public Result<String> completeBatch(String ids) {
        LambdaUpdateWrapper<WeeklyReportFeedback> updateWrapper = new UpdateWrapper<WeeklyReportFeedback>()
                .lambda()
                .in(WeeklyReportFeedback::getId, Arrays.asList(ids.split(",")))
                .set(WeeklyReportFeedback::getExecutionStatus, CommonMst.WEEKLYREPORT.EXECUTIONSTATUS)
                .set(WeeklyReportFeedback::getActualCompletionTime, new Date());
        this.weeklyReportFeedbackService.update(updateWrapper);
        return Result.OK("成功!");
    }

    /**
     * 生成周标题
     *
     * @return
     */
    @AutoLog(value = "周报反馈系统-生成周标题")
    @ApiOperation(value = "周报反馈系统-生成周标题", notes = "周报反馈系统-生成周标题")
    @RequestMapping(value = "/generateWeeklyTitle", method = {RequestMethod.POST, RequestMethod.GET})
    public Result<String> generateWeeklyTitle() {
        LocalDate localDate = LocalDateTime.now().toLocalDate();
        String date = localDate.toString();
        int year = localDate.getYear();//获取年
        int month = localDate.getMonthValue();//获取月
        int weekByWed = 0;//获取第几周
        try {
            weekByWed = DateUtil.getWeekByWed(date, CommonMst.WEEKLYREPORT.DATEFORMAT);
        } catch (Exception e) {
            log.error("周报反馈系统-生成周标题异常", e);
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        String title = sb.append(year).append("年").append(month).append("月第").append(weekByWed).append("周").toString();
        log.info("当前日期:{},属于当月的第{}周,生成的标题title:{}", date, weekByWed, title);
        return Result.OK(title);
    }


    /**
     * 查询IT部的所有员工信息
     *
     * @param
     * @return
     */
    @AutoLog(value = "软件运维计划表-查询IT部的所有员工信息")
    @ApiOperation(value = "软件运维计划表-查询IT部的所有员工信息", notes = "软件运维计划表-查询IT部的所有员工信息")
    @GetMapping(value = "/queryLoginUsersByDeptId")
    public Result<List<LoginUser>> queryLoginUsersByDeptId() {
        List<LoginUser> userByDeptId = commonApi.getUserByDeptId(CommonMst.SOFTWARE.IT_DEPT_ID);
        return Result.ok(userByDeptId);
    }


}
